const multer = require('multer');
const express = require('express');
const path = require('path');
const fs = require('fs-extra');
const iconv = require('iconv-lite');
const { idOcr } = require('./ai');

const router = express.Router();
const upload = multer({ storage: multer.memoryStorage() });

router.post('/submit', upload.array('files', 1000), async (req, res) => {
    const uuid = req.body.uuid;
    if (!uuid) {
        res.json({ message: 'uuid 不能为空', code: 400 });
        return;
    }
    const imageFolder = req.body.folder;
    console.log('imageFolder: ' + imageFolder);
    const uploadDir = path.join(global.__rootDir, 'uploads', uuid, imageFolder);
    console.log('uploadDir: ', uploadDir);
    fs.removeSync(uploadDir);
    await fs.mkdirp(uploadDir);
    const imagesPath = [];
    for (const file of req.files) {
        let originalName = file.originalname;
        // 解决中文文件名乱码问题
        originalName = iconv.decode(
            Buffer.from(originalName, 'latin1'),
            'utf-8'
        );
        const ext = path.extname(originalName);
        const fileName = path.basename(originalName, ext);
        const filePath = path.join(
            uploadDir,
            // 添加时间戳防止文件名重复
            fileName + '_' + Date.now() + ext
        );
        console.log('filePath: ', filePath);
        imagesPath.push(filePath);
        await fs.writeFile(filePath, file.buffer);
        console.log('file saved: ', filePath);
    }

    const censorType = req.body.censorType;
    console.log('censorType: ', censorType);
    if (censorType == 1) {
        return await censorActors({ imagesPath, res, uploadDir });
    }
    res.json({ code: 500, message: '暂不支持：' + censorType });
});

async function censorActors({ imagesPath, res, uploadDir }) {
    // 识别图片中证件的内容
    let ocrResults = [];
    for (const imagePath of imagesPath) {
        const ocrResult = await idOcr({ imagePath });
        if (!ocrResult) {
            throw new Error('ocr error');
        }
        delete ocrResult.nation
        delete ocrResult.is_foreign
        delete ocrResult.file_name
        ocrResults.push(ocrResult);
    }
    const ocrResStr = JSON.stringify(ocrResults);
    fs.writeFileSync(path.join(uploadDir, 'ocr.json'), ocrResStr, 'utf-8');
    const expiredIdCards = ocrResults.filter((each) => each.is_expired);
    res.json({
        code: 200,
        results: [
            {
                title: '过期证件',
                expiredIdCards,
            },
        ],
    });
}

module.exports = router;
